package com.axend.radarcommandset

import android.app.Activity
import android.content.Context
import android.location.LocationManager
import android.net.wifi.WifiSsid
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.axend.radarcommandsdk.R
import com.axend.radarcommandsdk.connect.DeviceNetworkConnect
import com.axend.radarcommandsdk.connect.bean.BleMsgEntity
import com.axend.radarcommandsdk.connect.bean.BleMsgTag
import com.axend.radarcommandsdk.connect.bean.DeviceType
import com.axend.radarcommandsdk.connect.bean.TcpMessageEntity
import com.axend.radarcommandsdk.connect.bean.TcpMsgTag
import com.axend.radarcommandsdk.connect.contract.IDeviceStatusCallback
import com.axend.radarcommandsdk.utils.BleUtils
import com.axend.radarcommandsdk.utils.LogUtil
import com.axend.radarcommandsdk.utils.ToastUtil
import com.axend.radarcommandsdk.utils.WifiUtils
import com.axend.radarcommandset.ui.theme.RadarCommandSetTheme
import com.axend.radarcommandset.widgets.LoadingDialog
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

/*tcp address 雷达连接地址*/
//const val radarTcpServiceUrl = "175.178.132.106,8801"
const val radarTcpServiceUrl = "34.223.29.230,8884"

/*wifi开头名称*/
const val WIFI_NAME_PREFIX = "AS_"

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            RadarCommandSetTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting()
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()

    }
}

@Composable
fun Greeting(modifier: Modifier = Modifier) {
    val context = LocalContext.current

    var showLoadingDialog by remember { mutableStateOf(false) }
    var loadingDialogText by remember { mutableStateOf(context.getString(R.string.tips_loading)) }
    var wifiSsid by remember { mutableStateOf("") }
    var wifiPassword by remember { mutableStateOf("") }

    if (showLoadingDialog) {
        LoadingDialog(loadingText = loadingDialogText) {
            showLoadingDialog = false
        }
    }

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        InputField(placeHolder = "请输入wifi名称", onValueChange = {
            wifiSsid = it
        }, value = wifiSsid)

        InputField(placeHolder = "请输入wifi密码", onValueChange = {
            wifiPassword = it
        }, value = wifiPassword)


        Button(modifier = Modifier
            .fillMaxWidth()
            .padding(top = 30.dp, start = 10.dp, end = 10.dp),
            onClick = {
                createDeviceConnect(context, DeviceType.WAAVE, wifiSsid, wifiPassword)
            }) {
            Text(text = "wavve(bluetooth)")
        }

        Button(modifier = Modifier
            .fillMaxWidth()
            .padding(top = 30.dp, start = 10.dp, end = 10.dp),
            onClick = {
                createDeviceConnect(context, DeviceType.ASSURE, wifiSsid, wifiPassword)
            }) {
            Text(text = "assure(bluetooth)")
        }
        var isVisible by remember {
            mutableStateOf(true)
        }
        if (isVisible) {
            Button(modifier = Modifier
                .fillMaxWidth()
                .padding(top = 30.dp, start = 10.dp, end = 10.dp),
                onClick = {
                    /*必须手动连接到wifi频段*/
                    createDeviceConnect(context, DeviceType.ASSURE_OLD, wifiSsid, wifiPassword)

                }) {
                Text(text = "assure(wifi)")
            }
        }

    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InputField(placeHolder: String, value: String, onValueChange: (String) -> Unit) {
    Box(
        modifier = Modifier.fillMaxWidth(1f),
        contentAlignment = Alignment.Center,
    ) {
        TextField(value = value, onValueChange = onValueChange,
            modifier = Modifier
                .padding(top = 10.dp, start = 10.dp, end = 10.dp)
                .fillMaxWidth()
                .background(color = colorResource(id = com.axend.radarcommandset.R.color.white))
                .border(1.dp, color = colorResource(id = com.axend.radarcommandset.R.color.white)),


            placeholder = {
                Text(
                    text = placeHolder,
                    fontSize = 16.sp
                )
            })
    }


}

/**
 * 创建设备连接
 * deviceType: 设备类型
 */

private fun createDeviceConnect(
    context: Context,
    deviceType: DeviceType,
    wifiSsid: String,
    wifiPassword: String
) {
    if (wifiSsid.isNullOrEmpty()) {
        ToastUtil.showShort(context, "请输入wifi名称")
        return
    }


    /*gps和蓝牙都要提示打开*/
    val locationManager: LocationManager =
        context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        ToastUtil.showShort(context, "请打开gps定位服务")
        return
    }

    if (!WifiUtils.getInstance(context).wifiStatus()) {
        ToastUtil.showShort(context, "请打开WIFI")
        return
    }

    if (!BleUtils.getInstance().isOpenBle()) {
        ToastUtil.showShort(context, "请打开蓝牙")
        return
    }

    /*Get permission 把需要的权限申请*/
    XXPermissions.with(context)
        .permission(Permission.Group.BLUETOOTH)
        .permission(Permission.ACCESS_COARSE_LOCATION)
        .permission(Permission.ACCESS_FINE_LOCATION)
        .request(object : OnPermissionCallback {
            override fun onGranted(
                permissions: MutableList<String>,
                allGranted: Boolean
            ) {
                if (!allGranted) {
                    ToastUtil.showShort(
                        context,
                        context.getString(R.string.permission_part_of)
                    )
                    return
                }

                /*以wifi 连接设备 需要手动连接设备wifi频段 例：AS_*/
                if (deviceType == DeviceType.ASSURE_OLD && WifiUtils.getInstance(context)
                        .getWifiSSID()?.startsWith(WIFI_NAME_PREFIX) != true
                ) {
                    ToastUtil.showShort(context, "请连接AS_开头wifi ssid")
                    return
                }
                ToastUtil.showShort(
                    context,
                    "开始进行${deviceType.getDeviceNameByString()}配网流程--DeviceNetworkConnect.createInstance"
                )
                /*调用createInstance创建设备连接*/
                DeviceNetworkConnect.createInstance(context = context as Activity,
                    iDeviceType = deviceType,
                    radarTcpServer = radarTcpServiceUrl,
                    wifiSSID = wifiSsid,
                    wifiPassWord = wifiPassword,
                    iDeviceStatusCallback = object : IDeviceStatusCallback {
                        override fun callBackDeviceStatus(status: Int) {
                            /* 连接状态值 11:成功 12:失败 13:中断  可自定义处理状态*/
                            LogUtil.i("设备返回状态:$status")
                            when (status) {
                                11 -> {
                                    ToastUtil.showShort(context, "设备连接成功")
                                }

                                12 -> {
                                    ToastUtil.showShort(context, "设备连接失败")
                                }

                                13 -> {
                                    ToastUtil.showShort(context, "设备连接中断")
                                }

                                else -> {
                                }
                            }
                        }

                        override fun callBackDeviceData(message: Any) {
                            LogUtil.i("设备返回消息:$message")
                            /*处理蓝牙消息示例*/
                            if (message is BleMsgEntity) {
                                when (message.bleMsgTag) {
                                    /*处理id*/
                                    BleMsgTag.GET_DEVICE_ID -> {
                                        ToastUtil.showShort(
                                            context,
                                            "Wavve设备ID:${message.body.toString()}"
                                        )
                                    }

                                    BleMsgTag.GET_ASSURE_DEVICE_ID -> {
                                        ToastUtil.showShort(
                                            context,
                                            "Assure设备ID:${message.body.toString()}"
                                        )
                                    }

                                    BleMsgTag.SET_STATUS -> {
                                        ToastUtil.showShort(context, "设置成功:${message.body}")
                                    }

                                    else -> {}
                                }
                            } else if (message is TcpMessageEntity) {
                                /*处理wifi 消息示例*/
                                when (message.msgTag) {
                                    TcpMsgTag.getID -> {
                                        val id: String = message.bodyObject.toString()
                                        ToastUtil.showShort(context, "雷达id：$id")
                                    }

                                    TcpMsgTag.getHardwareVersion -> {
                                        val hardwareVersion: String = message.bodyObject.toString()
                                        LogUtil.d("固件版本：$hardwareVersion")
                                    }

                                    TcpMsgTag.setFamilyWifiInfo ->                     //设置雷达WIFI账号与密码
                                        if (message.bodyObject as Boolean) {
                                            ToastUtil.showShort(context, "设置wifi账号和密码成功！")
                                        }

                                    TcpMsgTag.setDeviceIPAndPort ->                     //设置雷达IP地址与端口
                                        if (message.bodyObject as Boolean) {
                                            ToastUtil.showShort(context, "设置端口和IP成功！")
                                        }

                                    else -> {}
                                }
                            }
                        }

                    }
                ).deviceConnect()

            }

            override fun onDenied(
                permissions: MutableList<String>,
                doNotAskAgain: Boolean
            ) {
                if (doNotAskAgain) {
                    ToastUtil.showShort(
                        context,
                        "被永久拒绝授权，请手动授予蓝牙和位置权限"
                    )
                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                    XXPermissions.startPermissionActivity(context, permissions)
                } else {
                    ToastUtil.showShort(context, "获取蓝牙和位置权限失败")
                }
            }

        })


}


@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    RadarCommandSetTheme {
        Greeting()
    }


}
